package com.antdant.service;

import com.antdant.entity.LuckyDraw;
import com.antdant.entity.Prize;
import com.antdant.entity.User;
import com.antdant.repository.LuckyDrawRepository;
import com.antdant.utils.DataUtils;
import com.antdant.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author Lee Yunc
 * @Date 2021/3/15 17:37
 * @Description:
 * @Version 1.0
 */
@Slf4j
@Service
public class LuckyDrawService {

    @Resource
    private LuckyDrawRepository luckyDrawRepository;

    @Resource
    private UserService userService;

    /**
     * 增加一条抽奖记录
     *
     * @param prize
     * @param user
     * @return
     */
    public LuckyDraw addNewDrawRecord(Prize prize, User user) {
        //当前用户积分扣除，并保存到数据库
        user.setPoint(user.getPoint() - 20);
        userService.modifyUser(user);

        LuckyDraw luckyDraw = newLuckyDraw();
        luckyDraw.setPrizeId(prize.getId());
        luckyDraw.setPrizeName(prize.getPrizeName());
        luckyDraw.setUserId(user.getId());
        luckyDraw.setUserName(user.getUsername());
        return luckyDrawRepository.saveAndFlush(luckyDraw);
    }

    //抽奖记录初始化
    private LuckyDraw newLuckyDraw() {
        LuckyDraw luckyDraw = new LuckyDraw();
        luckyDraw.setCreateTime(DateUtils.getNowTime());
        luckyDraw.setStatus(0);
        return luckyDraw;
    }

    /**
     * 用户查询自己的抽奖记录
     *
     * @param current
     * @param size
     * @param user
     * @return
     */
    public Page<LuckyDraw> getDrawRecords(Integer current, Integer size, User user) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(current - 1, size, sort);
        return luckyDrawRepository.findAll(new Specification<LuckyDraw>() {
            @Override
            public Predicate toPredicate(Root<LuckyDraw> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Predicate predicate = criteriaBuilder.equal(root.get("userId"), user.getId());
                return predicate;
            }
        }, pageable);
    }

    /**
     * 管理员查询所有抽奖记录
     *
     * @param current
     * @param size
     * @param luckyDraw
     * @return
     */
    public Page<LuckyDraw> getAllDrawRecords(Integer current, Integer size, LuckyDraw luckyDraw) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(current - 1, size, sort);
        return luckyDrawRepository.findAll(new Specification<LuckyDraw>() {
            @Override
            public Predicate toPredicate(Root<LuckyDraw> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<>();
                if (DataUtils.isNotEmptyStr(luckyDraw.getPrizeName())) {
                    list.add(criteriaBuilder.equal(root.get("prizeName"), luckyDraw.getPrizeName()));
                }
                if (DataUtils.isNotEmptyStr(luckyDraw.getUserName())) {
                    list.add(criteriaBuilder.equal(root.get("userName"), luckyDraw.getUserName()));
                }
                return criteriaBuilder.and(list.toArray(new Predicate[list.size()]));
            }
        }, pageable);
    }

    /**
     * 根据id删除抽奖记录
     *
     * @param drawRecordId
     * @return
     */
    public Boolean deleteDrawRecord(Integer drawRecordId) {
        try {
            luckyDrawRepository.deleteById(drawRecordId);
            return true;
        } catch (RuntimeException e) {
            return false;
        }
    }

    /**
     * 兑换奖品
     *
     * @param drawRecordId
     * @return
     */
    public LuckyDraw updateDrawRecordStatus(Integer drawRecordId) {
        LuckyDraw luckyDraw = luckyDrawRepository.findById(drawRecordId).orElse(null);
        assert luckyDraw != null;
        luckyDraw.setStatus(1);
        luckyDraw.setRedeemTime(DateUtils.getNowTime());
        return luckyDrawRepository.saveAndFlush(luckyDraw);
    }
}
